<?php
namespace app\index\controller;

use app\BaseController;

use app\index\logic\AuthLogic;
use app\index\logic\UserReportLogic;
use app\model\Token;
use app\model\User;
use app\model\Wx;
use app\service\WxService;
use think\facade\Request;

class Index extends BaseController
{
    public function login(){

        $param = Request::post();

        if(!isset($param['encryptedData']) || empty($param['encryptedData'])) fail('encryptedData参数不能为空');
        $encryptedData = trim($param['encryptedData']);

        if(!isset($param['iv']) || empty($param['iv'])) fail('iv参数不能为空');
        $iv = trim($param['iv']);

        if(!isset($param['openid']) || empty($param['openid'])) fail('openid参数不存在');
        $openid = trim($param['openid']);

        $wxModel = new Wx();
        $openInfo = $wxModel->getWxInfByOpenid($openid,'wx_id,wx_session_key');
        if(!$openInfo)   fail('请微信授权');

        $sessionKey = $openInfo['wx_session_key'];
        $wxService = new WxService();
        $rt = $wxService->dataCrypt($sessionKey,$encryptedData,$iv);

        if(!$rt)    fail('验证失败，请稍后重试');

        $phone = $rt['phoneNumber'];
        $userModel = new User();
        $info = $userModel->getUserIndexInfoByPhone($phone,'user.id,user.pername,user.phone,user.pwd,user.position,user.integral,user.orgid,org.orgname,org.floor,org.oreaddress,org.lng,org.lat,org.ispersonnel,org.isphoto');
        if(!$info)  fail('不是工作人员',[],402);

        //绑定关系
        $wx = [
            'wx_uid' => $info['id'],
        ];
        $wxModel->updateWxInfoByWhere(['wx_id'=>$openInfo['wx_id']],$wx);
        $tokenModel = new Token();
        $info['token'] = $tokenModel->generateToken($info['id']);

        //判断周报或者月报是否提交过
        $info['weekReport'] = UserReportLogic::checkReportCreated($info['id']);
        $info['monthReport'] = UserReportLogic::checkReportCreated($info['id'],2);;
        success($info);
    }

    /*
     * 小程序登录
     */
    public function wxLogin(){

        $param = Request::get();
        if(!isset($param['code']) || empty($param['code'])) fail('code不存在');
        $code = trim($param['code']);

        $authLogic = new AuthLogic();
        success($authLogic->codeLogin($code));
    }

    public function logout(){

    }
}
